/**
 * 静态分析测试用例
 *
 * Created by yangyunze on 2021/01/04.
 */
const chai = require('chai');
chai.use(require('chai-http'));

const common = require('./../../common');
const Administrator = require('./../../../models/administrator');
const uri = require('./../uri');
const benchmark = require('./../../../benchmark/static-analyze/gjb.json');

module.exports = describe('/POST project-versions/:projectVersionId/static-analyze.json', function () {
  const administrator = new Administrator();
  let project = {};
  let projectVersion = {};
  let newUser;

  function url(projectVersionId) {
    return `/project-versions/${projectVersionId}/static-analyze.json`;
  }

  before(function (done) {
    administrator.login()
      .then(() => administrator.createRandomTester())
      .then((tester) => {
        newUser = tester;
        return newUser.createRandomProject('c++');
      })
      .then((res) => {
        project = res;
        return project.createStaticAnalyzeVersion(
          [],
          benchmark.files,
          newUser
        );
      })
      .then((res) => {
        projectVersion = res;
        done();
      })
      .catch(done);
  });
  after(function (done) {
    administrator.removeUsers([newUser.userId])
      .then(() => {
        done();
      })
      .catch(done);
  });

  common.should.be.user(uri, url, 'post');
  common.should.be.tester(uri, url, 'post');

  // 静态分析
  it('it should analyze successfully', function (done) {
    projectVersion.rootDirectory.staticAnalyze()
      .then((res) => {
        res.should.have.status(202);
        common.should.be.taskMessage(res.body);
      })
      .then(() => projectVersion.project.creator.waiting4TasksOfVersionFinished(
        projectVersion.versionId
      ))
      .then(done)
      .catch(done);
  });

  // 重复分析
  it('it should success when analyze again without clear the analyze result', function (done) {
    projectVersion.rootDirectory.staticAnalyze()
      .then((res) => {
        res.should.have.status(202);
        done();
      })
      .catch(done);
  });
  // 当没有选择解析文件时执行静态分析报400
  it('it should failed when analyze without select files', function (done) {
    const params = { fileIds: [] };
    projectVersion.rootDirectory.staticAnalyze(params)
      .then((res) => {
        res.should.have.status(400);
        done();
      })
      .catch(done);
  });
  // 当模板不存在时执行静态分析报404
  it('it should failed when analyze without an analyze template', function (done) {
    project.removeVersion(projectVersion.versionId)
      .then(() => project.createRandomVersion())
      .then((res) => {
        projectVersion = res;
        return projectVersion.updateVersionFiles(benchmark.files);
      })
      .then(() => projectVersion.rootDirectory.staticAnalyze())
      .then((res) => {
        res.should.have.status(404);
        done();
      })
      .catch(done);
  });
});
